import { ColumnHeightOutlined, ReloadOutlined, SettingOutlined } from "@ant-design/icons";
import { Button, Checkbox, Dropdown, Tooltip } from "antd";
import type { ColumnsType } from "antd/es/table";
import type React from "react";
import { useMemo } from "react";

interface CheckboxDropdownProps {
	columns: ColumnsType<any>;
	selectedValues?: string[];
	onChange?: (values: string[]) => void;
}

const CheckboxDropdown: React.FC<CheckboxDropdownProps> = ({ columns, selectedValues = [], onChange }) => {
	// 过滤并转换选项
	const options = useMemo(
		() =>
			columns
				.filter((col) => col.key !== "operation" && col.key !== "sort") // 过滤掉操作列和排序列
				.map((col) => ({
					label: col.title,
					value: col.dataIndex,
				})),
		[columns],
	);

	const handleChange = (checkedValues: string[]) => {
		onChange?.(checkedValues);
	};

	const dropdownContent = (
		<div
			onClick={(e) => e.stopPropagation()}
			style={{
				background: "#ffffff",
				borderRadius: 8,
				boxShadow: "0 3px 6px rgba(0, 0, 0, 0.1)",
				padding: "5px",
			}}
		>
			<Checkbox.Group
				value={selectedValues}
				onChange={handleChange}
				style={{
					display: "block",
					padding: "8px 0",
					width: "100%",
				}}
			>
				{options.map((opt, idx) => (
					<div key={opt.value} style={{ padding: "8px 12px" }}>
						<Checkbox key={`${opt.value}_${idx}`} value={opt.value} >
							<span
								style={{
									whiteSpace: "nowrap",
									fontSize: 14,
								}}
							>
								{opt.label}
							</span>
						</Checkbox>
					</div>
				))}
			</Checkbox.Group>
		</div>
	);

	return (
		<Dropdown
			dropdownRender={() => dropdownContent}
			overlayStyle={{
				padding: 0,
			}}
		>
			<Tooltip title="列设置">
				<Button type="text" icon={<SettingOutlined />} />
			</Tooltip>
		</Dropdown>
	);
};

interface TableToolbarProps {
	onRefresh?: () => void;
	onSizeChange?: (size: "large" | "middle" | "small") => void;
	columns?: ColumnsType<any>;
	selectedValues?: string[];
	onColumnChange?: (values: string[]) => void;
	children?: React.ReactNode;
}

export const TableToolbar: React.FC<TableToolbarProps> = ({
	onRefresh,
	onSizeChange,
	columns,
	selectedValues,
	onColumnChange,
	children,
}) => {
	return (
		<div className="flex gap-2">
			{children}
			<Tooltip title="刷新">
				<Button type="text" icon={<ReloadOutlined />} onClick={onRefresh} />
			</Tooltip>
			<Dropdown
				menu={{
					items: [
						{ key: "large", label: "大" },
						{ key: "middle", label: "中" },
						{ key: "small", label: "小" },
					],
					onClick: ({ key }) => {
						onSizeChange?.(key as "large" | "middle" | "small");
					},
				}}
			>
				<Tooltip title="紧凑">
					<Button type="text" icon={<ColumnHeightOutlined />} />
				</Tooltip>
			</Dropdown>
			{columns && onColumnChange && (
				<CheckboxDropdown columns={columns} selectedValues={selectedValues} onChange={onColumnChange} />
			)}
		</div>
	);
};
